import {ChangeDetectorRef, Component} from '@angular/core';
import {
    AlertController,
    IonicPage,
    NavController,
    NavParams,
    ToastController,
    Platform,
    ItemSliding,
    Events
} from 'ionic-angular';
import {FileTransfer, FileUploadOptions, FileTransferObject} from '@ionic-native/file-transfer';
import $ from "jquery";
import * as moment from 'moment';

import {ClientNoteListProvider} from "../../../../providers/client/client-note/client-note-list/client-note-list.provider";
import {
    ClientNoteListModel,
    ProgressSearch,
    ListPageTitle
} from "../../../../model/pages/client/client-note/client-note-list/client-note-list.model";
import {ClientNoteEditProvider} from "../../../../providers/client/client-note/client-note-edit/client-note-edit.provider";
import {RecorderService} from "../../../../services/recorder.service";
import {FileService} from '../../../../services/native/file/file.service';
import {LocalStorageService} from "../../../../services/native/local-storage/local-storage.service";
import {MessageBushService} from "../../../../services/common/message-bush.service";
import {PermissionsService} from "../../../../services/native/permissions/permissions.service";
import {SideMenuService} from "../../../../services/common/side-menu.service";
import {TabsPage} from "../../../tabs/tabs";
import {ToastService} from '../../../../services/common/toast.service';
import {LoadingService} from "../../../../services/common/loading.service";
import {ProgressModel} from "../../../../model/common/page-progress.model";

@IonicPage()
@Component({
    selector: 'page-client-note-list',
    templateUrl: 'client-note-list.html',
    providers: [
        FileTransfer,
        ClientNoteListProvider,
        ClientNoteEditProvider,
        RecorderService,
        FileService,
        LocalStorageService,
        PermissionsService,
        SideMenuService,
        ToastService
    ]
})
export class ClientNoteListPage {
    // 客户全部笔记
    private clientNoteListModels: Array<ClientNoteListModel> = [];
    // 客户id
    private clientNumber: string;
    // 文字(1)、语音(2)笔记切换
    private noteType: number = 1;
    // 页面进入底部按钮显示
    private enterStatus: boolean = true;
    // 确认弹框
    private alertObj: any;
    // 是否请求过笔记列表
    private requestStatus: boolean;

    // 语音时长
    private voiceLength: number;
    // 当前语音的id
    private voiceId: any;
    // 语音播放计时
    private playTimerLength: number = null;
    // 语音播放计时器
    private playerVoiceTimer: any;
    // 云端语音资源下载时间计时
    private downloadTimerLength: number = 0;
    // 云端语音资源下载时间计时器
    private voiceDownloadTimer: any;
    // 标记当前下载语音笔记的ID
    private currentVoiceId: any;
    // 语音播放停止切换
    private switchPlayOrStop: boolean = true;

    // 全部笔记按年排列
    private allNoteYearQueue: any = {};
    // 全部笔记日期ID对象
    private allNoteDateIdList: any = {};

    // 筛选条件
    private filterData: ProgressSearch = new ProgressSearch();

    isLoaded: boolean = false;

    // 录音组件是否加载
    private audioStatus: boolean = true;
    // 录音按钮
    private audioBtn: number = 1;
    // 跳转页面数据
    private page: any = {};
    // 单项跟进对象
    private clientProgress: ProgressModel = new ProgressModel();
    // 页面title
    private pageTitle: any;

    constructor(public navCtrl: NavController,
                public navParams: NavParams,
                public alertCtrl: AlertController,
                public toastCtrl: ToastController,
                public platform: Platform,
                private clientNoteListProvider: ClientNoteListProvider,
                private clientNoteAddProvider: ClientNoteEditProvider,
                private recorderService: RecorderService,
                private fileService: FileService,
                private ref: ChangeDetectorRef,
                private permissionsService: PermissionsService,
                private sideMenuService: SideMenuService,
                public tabsPage: TabsPage,
                public toastService: ToastService,
                private load: LoadingService,
                private event: Events,) {
        this.platform.pause.subscribe(() => {
            this.stopVoice();
            this.switchPlayOrStop = true;
        })
    }

    public backButtonHandle = () => this.backClickHandle();

    ionViewDidLoad() {
        let baseInfo = this.navParams.get('base');
        if (baseInfo.clientType == 1) {
            this.filterData.clientName = baseInfo.clientName;
            this.filterData.clientPhone = baseInfo.clientPhone;
            this.filterData.clientType = 1;
            this.filterData.clientId = baseInfo.clientId;
        } else {
            this.filterData.clientId = this.navParams.get('base').clientId;
            this.filterData.clientType = baseInfo.clientType;
        }
        this.pageTitle = ListPageTitle[this.filterData.clientType];
        this.getInfoList(null, 0);
        this.initProgress();
        this.subscribeEvents();
    }

    ionViewDidEnter() {
        this.clientNumber = this.navParams.get("clientNum");
        setTimeout(() => {
            this.enterStatus = true;
        }, 100);
        this.audioStatus = true;
    }

    ionViewWillUnload() {
        this.voiceLength = 0;
        this.stopVoice();
        this.event.unsubscribe('progress create');
        this.event.unsubscribe('progress update');
        this.event.unsubscribe('progress del');
        this.event.unsubscribe('progress search');
    }

    // 订阅跟进变更
    subscribeEvents() {
        this.event.subscribe('progress create', () => {
            this.getInfoList(null, 0);
            this.initProgress();
        });
        this.event.subscribe('progress update', () => {
            this.getInfoList(null, 0);
            this.initProgress();
        });
        this.event.subscribe('progress del', () => {
            this.getInfoList(null, 0);
            this.initProgress();
        });
        this.event.subscribe('progress search', () => {
            this.getInfoList(null, 0);
            this.initProgress();
        });
    }

    // 初始化一个跟进
    initProgress() {
        this.clientProgress.calendarTaskId = '';
        this.clientProgress.content = '';
        this.clientProgress.contentType = 1;
        this.clientProgress.createdTime = null;
        this.clientProgress.noteType = 3;
        this.clientProgress.voiceLength = null;
        this.clientProgress.voiceUrl = '';
        this.clientProgress.clientNumber = this.navParams.get('clientNum');
    }

    // 获取跟进列表
    getInfoList(done, notLoading) {
        this.isLoaded = false;
        this.requestStatus = false;
        this.allNoteYearQueue = {};
        this.allNoteDateIdList = {};
        if (notLoading !== 1) {
            this.load.showLoading();
        }
        this.clientNoteListProvider.getProgressList(this.filterData).subscribe((res) => {
            this.clientNoteListModels = res.notes;
            this.isLoaded = true;
            this.ref.detectChanges();
            this.requestStatus = true;
            done ? done() : null;

            this.getNoteTimeList(this.clientNoteListModels, this.allNoteYearQueue, this.allNoteDateIdList);
            this.load.dismissLoading();
        }, error => {
            this.clientNoteListModels = [];
            this.requestStatus = true;
            done ? done() : null;
            this.load.dismissLoading();
        });
    }

    // 下拉刷新
    doRefresh(refresher) {
        this.getInfoList(() => {
            refresher.complete();
        }, 1);
    }

    /**
     * 获取笔记时间列表
     * @param {Array<ClientNoteListModel>} noteList 列表
     * @param yearQUeue 年度时间列表
     * @param dateIdList 日期时间列表
     */
    getNoteTimeList(noteList: Array<ClientNoteListModel>, yearQUeue: any, dateIdList: any) {
        let yearList = [], dateList = [];
        for (let n = 0; n < noteList.length; n++) {
            let year = moment(Number(noteList[n].createdTime) * 1000).year();
            let date = moment(Number(noteList[n].createdTime) * 1000).format('YYYY-MM-DD');
            let id = noteList[n].id;
            if (noteList[n].createdTime && dateList[dateList.length - 1] != date) {
                dateList.push(date);
                dateIdList[id] = 'date'
            }
            if (noteList[n].createdTime && yearList[yearList.length - 1] != year) {
                yearList.push(year);
                yearQUeue[id] = year;
            }
        }

    }

    // 获取笔记类型标记
    getNoteType(item: any) {
        const types = ['[销售]', '[增员]', '[其他]', '[系统]'];
        return types[item.noteType - 1]
    }

    // 切换笔记类型
    switchType(e, num: number) {
        e.stopPropagation();
        e.preventDefault();
        if (num == 1) {
            this.noteType = 1;
        } else if (num == 2) {
            this.noteType = 2;
        } else {
            this.noteType = 1;
        }
    }

    // 到跟进筛选
    goToNoteFilter() {
        this.audioStatus = false;
        this.navCtrl.push('ClientNoteFilterPage', {
            filterData: this.filterData,
            callback: this.callbak
        })
    }

    // 传递回调
    callbak = (param: ProgressSearch) => {
        return new Promise((reslove, reject) => {
            console.log(param);
            if (param) {
                this.filterData.noteTypes = param.noteTypes;
                !param.starttime ? delete this.filterData.starttime : this.filterData.starttime = param.starttime;
                !param.endtime ? delete this.filterData.endtime : this.filterData.endtime = param.endtime;
                console.log(this.filterData);
                reslove();
            } else {
                reject();
            }
        })
    };

    // 新增文字跟进
    addNewProgress() {
        this.initProgress();
        this.navCtrl.push('ClientNoteEditPage', {
            params: this.clientProgress,
            base: this.navParams.get('base'),
            id: this.clientNumber
        })
    }

    // 跳转到编辑笔记
    editNote(clientNoteListModel: ClientNoteListModel) {
        if (clientNoteListModel.noteType == 4||clientNoteListModel.sourceType==2) {
            return false;
        }
        this.stopVoice();
        this.audioStatus = false;
        this.navCtrl.push('ClientNoteEditPage', {
            opType: 2,
            params: clientNoteListModel,
            base: this.navParams.get('base'),
            id: this.clientNumber
        });
    }

    // 新增语音笔记
    voiceNoteGoAddPage() {
        this.stopVoice();
        this.audioStatus = false;
        this.clientProgress.contentType = 2;
        this.navCtrl.push('ClientNoteEditPage', {
            params: this.clientProgress,
            base: this.navParams.get('base'),
            id: this.clientNumber
        })
    }

    /*// 录音成功跳转至跟进新增
    recordSuccess($event) {
        this.audioStatus = false;
        this.clientProgress.contentType = 2;
        this.clientProgress.voiceUrl = $event.voiceUrl;
        this.clientProgress.voiceLength = $event.voiceLength;
        this.voiceNoteGoAddPage();
    }*/

    /**
     * 滑动删除笔记
     * @param e
     * @param item
     * @param {number} index
     */
    delete(e, item: any, index: number, itemSliding: ItemSliding, type) {
        e.stopPropagation();
        e.preventDefault();
        this.showConfirm('确定删除？',
            () => {
                this.deleteNote(item.id, index, type);
                item.voiceUrl ? this.deleteVoiceSource(item.voiceUrl) : null;
            },
            () => {
                itemSliding.close();
            });
    }

    // 删除笔记请求
    deleteNote(id, index, type) {
        this.clientNoteAddProvider.deleteNote(id).subscribe((res) => {
            this.deleteCalc(id, index, type);
            MessageBushService.setMessage(MessageBushService.keys.clientDetailDataUpdated, "1");
        }, err => {
            if (err.status == 500) {
                this.toastService.showToast("删除失败");
            }
        })
    }

    // 删除语音文件请求
    deleteVoiceSource(fileId) {
        this.fileService.deleteFile(fileId).subscribe((res) => {
            console.log(res)
        })
    }

    // 删除笔记列表运算
    deleteCalc(id, index, type) {
        let allIndex, clueIndex;
        let allId, clueId;
        // 删除笔记数据遍历
        for (let a = 0; a < this.clientNoteListModels.length; a++) {
            if (this.clientNoteListModels[a].id == id) {
                allIndex = a;
                allId = this.clientNoteListModels[a].id;
            }
        }
        // 转接笔记时间标记点
        this.switchNoteTime(allId, allIndex, this.clientNoteListModels, this.allNoteYearQueue, this.allNoteDateIdList);
        // 数据删除
        if (allId) {
            this.clientNoteListModels.splice(allIndex, 1)
        }
    }

    /**
     * 删除笔记时转接笔记时间标记
     * @param id 当前要删除的笔记id
     * @param index 当前要删除的笔记在其列表中的序列号
     * @param {Array<ClientNoteListModel>} models 当前要删除的笔记所在的列表
     * @param year 要删除的笔记所在的列表的年纪列表
     * @param date 要删除的笔记所在的列表日期列表
     * @returns {boolean}
     */
    switchNoteTime(id, index, models: Array<ClientNoteListModel>, year, date) {
        if (!models[index + 1] || !models[index] || !id) {
            return false;
        }
        // 年纪转接
        if (year[id] && !year[models[index + 1].id]) {
            year[models[index + 1].id] = year[id];
            year[id] = null;
        }
        // 日期转接
        if (date[id] && !date[models[index + 1].id]) {
            date[models[index + 1].id] = date[id];
            date[id] = null;
        }
    }

    // 播放或停止录音
    playOrStop(e, name, id, length) {
        e.stopPropagation();
        e.preventDefault();
        if (!this.platform.is('cordova')) {
            return;
        }
        if (!this.switchPlayOrStop) {
            this.stopVoice();
            if (this.currentVoiceId == id) {
                this.switchPlayOrStop = true;
                return false;
            }
        } else {
            this.switchPlayOrStop = false;
        }
        this.currentVoiceId = id;
        this.playTimerLength = null;
        this.voiceId = null;
        // 清除下载语音计时器
        if (this.voiceDownloadTimer) {
            clearInterval(this.voiceDownloadTimer)
        }
        this.downloadTimerLength = 0;
        this.calcDownloadTimer();
        // 下载语音
        this.fileService.getFile(name, name).subscribe((res) => {
            this.recorderService.releasePlay();
            this.recorderService.startPlay(this.recorderService.getPlatformFileUrl(res.fileUrl));
            // 清除下载语音计时器
            clearInterval(this.voiceDownloadTimer);
            this.downloadTimerLength = 0;
            // 播放计时器切换
            this.playTimerLength = length;
            this.voiceId = id;
            if (this.playerVoiceTimer) {
                clearInterval(this.playerVoiceTimer);
            }
            this.calcTimer();
        }, error => {
            this.toastService.showToast('语音下载失败');
            clearInterval(this.voiceDownloadTimer);
        });
    }

    // 下载计时器
    calcDownloadTimer() {
        this.downloadTimerLength = 0;
        this.voiceDownloadTimer = setInterval(() => {
            this.downloadTimerLength++;
        }, 1000)
    }

    // 播放计时器
    calcTimer() {
        this.playerVoiceTimer = setInterval(() => {
            this.playTimerLength--;
            if (this.playTimerLength <= 0) {
                if (!this.switchPlayOrStop) {
                    this.switchPlayOrStop = true;
                }
                clearInterval(this.playerVoiceTimer);
                this.playTimerLength = null;
                this.voiceId = null;
            }
        }, 1000)
    }

    // 停止播放音频
    stopVoice() {
        clearInterval(this.playerVoiceTimer);
        this.recorderService.stopPlay();
        this.recorderService.pausePlay();
        this.recorderService.releasePlay();
        this.voiceId = null;
    }

    // 页面返回
    backClickHandle() {
        this.stopVoice();
        this.audioStatus = false;
        this.navCtrl && this.navCtrl.pop(null, null);
    }

    /**
     * 确认框
     *
     * @private
     * @param {any} msg 询问的消息
     * @param {any} okCallback 用户点击确定后的回调
     * @param {any} cancelCallback 用户点击取消后的回调
     * @memberof ScheduleAddPage
     */
    showConfirm(msg, okCallback, cancelCallback) {
        if (this.alertObj) return;
        this.alertObj = this.alertCtrl.create({
            enableBackdropDismiss: false,
            message: msg,
            buttons: [{
                text: '取消',
                handler: cancelCallback
            }, {
                text: '确定',
                handler: okCallback
            }]
        });
        this.alertObj.onDidDismiss(() => this.alertObj = null);
        this.alertObj.present();
    }
}
